package com.wf.course.web;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.PutObjectRequest;
import com.utils.security.UUIDGenerator;

public class PutObjectProgressListener implements ProgressListener {
		
		
		private static long bytesWritten = 0;
	    private static long totalBytes = -1;
	    private static boolean succeed = false;
	    private static double percent  = 0.0;
	    
	    public void progressChanged(ProgressEvent progressEvent) {
	        long bytes = progressEvent.getBytes();
	        ProgressEventType eventType = progressEvent.getEventType();
 	        switch (eventType) {
	        case TRANSFER_STARTED_EVENT:
	            System.out.println("Start to upload......");
	            break;
	        case REQUEST_CONTENT_LENGTH_EVENT:
	            this.totalBytes = bytes;
	            System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
	            break;
	        case REQUEST_BYTE_TRANSFER_EVENT:
	            this.bytesWritten += bytes;
	            if (this.totalBytes != -1) {
	                int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
	                System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
	            } else {
	                System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
	            }
	            break;
	        case TRANSFER_COMPLETED_EVENT:
	            this.succeed = true;
	            System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
	            this.bytesWritten = 0;
	            this.percent = 0.0;
	            break;
	        case TRANSFER_FAILED_EVENT:
	            System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
	            break;
	        default:
	            break;
	        }
	    }
	    public boolean isSucceed() {
	        return succeed;
	    }
	    
	    /**
	     * 文件上传
	     * @param bucketName
	     * @param key
	     * @param inputStream
	     */
	    public static void uploadProgress(String bucketName,String key,InputStream inputStream ) throws EOFException {
	    	//初始化client
			OSSClient client = new OSSClient(Constants.OSS_ENDPOINT,Constants.OSS_ACCESS_ID, Constants.OSS_ACCESS_KEY);
	    	 // 带进度条的上传 
			 client.putObject(new PutObjectRequest(bucketName, key, inputStream).
			        <PutObjectRequest>withProgressListener(new PutObjectProgressListener()));
	    }
	    /**
	     * 上传文件，返回路径
	     * @param file
	     * @param folder
	     * @param bucketName
	     * @return
	     * @throws IOException
	     */
	    public static String addFile(Object file , String folder , String bucketName) throws IOException{
			 InputStream content  = null;
			 ObjectMetadata meta = null;
			 String  extension = "";
			if(file!=null){
				if(file instanceof CommonsMultipartFile){
					CommonsMultipartFile file1  = (CommonsMultipartFile)file;
					//文件扩展名
					 String fileName = file1.getOriginalFilename();
					 if(fileName.lastIndexOf(".")!=-1){
						 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
					 }
					// 获取指定文件的输入流
					  content =file1.getInputStream();
					    // 创建上传Object的Metadata
					   meta = new ObjectMetadata();
					    // 必须设置ContentLength
					    meta.setContentLength(file1.getSize());
	 				 // 设置content type  
					    String strContentType = file1.getContentType();  
					    meta.setContentType(strContentType);  
				}
				else if(file instanceof MultipartFile){
					MultipartFile	file2 = (MultipartFile)file;
					 String fileName = file2.getOriginalFilename();
					 if(fileName.lastIndexOf(".")!=-1){
						 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
					 }
					// 获取指定文件的输入流
					  content =file2.getInputStream();
					    // 创建上传Object的Metadata
					   meta = new ObjectMetadata();
					    // 必须设置ContentLength
					    meta.setContentLength(file2.getSize());
				}
				else if(file instanceof File){
					File file3 = (File)file;
					//文件扩展名
					 String fileName = file3.getName();
					 if(fileName.lastIndexOf(".")!=-1){
						 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
					 }
					// 获取指定文件的输入流
					  content =new FileInputStream(file3);
					    // 创建上传Object的Metadata
					  meta = new ObjectMetadata();
					    // 必须设置ContentLength
					  meta.setContentLength(file3.length());
				}
				else {
					return null;
				}
			}
		    String uuid = UUIDGenerator.getUUID(false);
		    
		    // 带进度条的上传 
		    uploadProgress(bucketName,folder+"/"+uuid+extension,content);

		    return folder+"/"+uuid+extension;
		}
	    /**
	     * 获取文件上传进度
	     * @param file
	     * @return
	     */
	    public static  double getPercent(Object file) throws IOException{
				InputStream content  = null;
				
				if(file!=null){
					if(file instanceof CommonsMultipartFile){
						CommonsMultipartFile file1  = (CommonsMultipartFile)file;
						// 获取指定文件的输入流
						 content =file1.getInputStream();
					}
					else if(file instanceof MultipartFile){
						MultipartFile	file2 = (MultipartFile)file;
						// 获取指定文件的输入流
						 content =file2.getInputStream();
					}
					else if(file instanceof File){
						File file3 = (File)file;
						// 获取指定文件的输入流
						 content =new FileInputStream(file3);
					}
					
					totalBytes = Long.valueOf(content.available());
					if(totalBytes != 0 ){
						if( percent <100.0){
							percent =  (bytesWritten* 100/totalBytes );
							System.out.println("上传进度："+percent+"%");
						}
						
					} 
				}

			    return percent;
			}
	    
	    
}
